// base64转blob
function dataURLtoBlob (dataurl) {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

function downloadFile (url, name = '未命名文件') {
  let a = document.createElement("a")
  a.setAttribute("href", url)
  a.setAttribute("download", name)
  a.setAttribute("target", "_blank")
  let clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
}

function downloadFileByBlob (blob, name) {
  let myUrl = URL.createObjectURL(blob)
  downloadFile(myUrl, name)
}

function downloadFileByBase64 (base64, name) {
  let myBlob = dataURLtoBlob(base64)
  downloadFileByBlob(myBlob, name)
}

function downloadFileByText (text, name) {
  let blob = new Blob([text], { type: 'text/plain' });
  downloadFileByBlob(blob, name)
}

function blob2String (blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function (event) {
      resolve(reader.result)
    };
    reader.onerror = function (e) {
      reject(e)
    }
    reader.readAsText(blob);
  })
}

export default {
  blob2String,
  downloadFileByBase64,
  downloadFileByText,
  downloadFileByBlob
}
